import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';

import 'package:flutter_spinkit/flutter_spinkit.dart';
import '../../model/ftpfile.dart';
import '../../helper/Helper.dart';
import '../../helper/channelHelper.dart';

import '../../helper/uidata.dart';

import '../../model/space_item.dart';
import 'fileSpace_helper.dart';

import '../../helper/upload_helper.dart';

class FileSpaceFtpFilePage extends StatefulWidget {
  @override
  FileSpaceFtpFilePage(this.spaceId, this.tag, this.ifCanAdd,
      {this.ifAppbar = false});
  final bool ifAppbar;
  final String spaceId;
  final String tag;
  final bool ifCanAdd;

  @override
  FileSpaceFtpFilePageState createState() => new FileSpaceFtpFilePageState();
}

class FileSpaceFtpFilePageState extends State<FileSpaceFtpFilePage> {
  List<FtpFile> RList = <FtpFile>[];
  bool isEnd = false;
  ScrollController _scrollController = new ScrollController();
  bool firstLoading = true;
  int pageSize = 20;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        getMore();
      }
    });

    getNewer();
  }

  Future<Null> delete(FtpFile r1) async {
    // await addOne();

    await FtpFile.Delete(r1);
    setState(() {
      RList.remove(r1);
    });
  }

  onDeleted(FtpFile r1) => {
        setState(() {
          RList.remove(r1);
        })
      };

  Future<Null> getMore() async {
    // await addOne();

    if (isEnd == true) return;
    int page = RList.length ~/ pageSize;
    var list1 = await FtpFile.GetList(widget.spaceId, 0, page + 1, pageSize);
    var list2 =
        list1.where((p) => RList.any((x) => x.ID == p.ID) == false).toList();

    setState(() {
      if (list1.length < pageSize) isEnd = true;
      RList.insertAll(RList.length, list2);
    });
  }

  Widget getFButton() {
    return FloatingActionButton(
      child: Icon(Icons.file_upload),
      onPressed: () async {
        File file = File((await Helper.getFilePickPath())!);
        var pb1 = file.existsSync();
        if (pb1 == false) {
          SnackBar(
            content: Text("文件不存在！"),
          );
          return;
        }
        var guid = Helper.GetGuid();
        var size1 = file.lengthSync();
        var x1 = new FtpFile(0, guid, UIData.CurrentUser!.Guid, widget.spaceId,
            file.path, Helper.DateTimeNowString(), -1, size1, widget.tag);

        var pbx = await FtpFile.Add(x1);
        if (!pbx) return;
        UploadHelper.UpLoad(
            file.absolute.path, widget.tag, guid, widget.spaceId,
            fType: -1);
        ChannelHelper.showToast("已将文件添加到上传列表");
      },
    );
  }

  Future<Null> getNewer() async {
    var list1 = await FtpFile.GetList(widget.spaceId, 0, 1, pageSize);
    setState(() {
      firstLoading = false;
    });

    if (list1.length == 0) return;

    var list2 =
        list1.where((p) => RList.any((x) => x.ID == p.ID) == false).toList();
    if (list2.length == 0) return;

    list2.insertAll(list2.length, RList);

    setState(() {
      firstLoading = false;
      RList = list2;
    });
  }

  @override
  Widget build(BuildContext context) {
    if (RList == null) return new Container();
    // TODO: implement build
    return new Scaffold(
        appBar: widget.ifAppbar ? AppBar(title: Text(widget.tag)) : null,
        floatingActionButton: widget.ifCanAdd ? getFButton() : null,
        body: firstLoading == true
            ? Center(
                child: SpinKitCircle(
                color: Colors.blue,
              ))
            : Container(
                margin: EdgeInsets.only(top: 8.0),
                child: new RefreshIndicator(
                  child: ListView.builder(
                    itemCount: RList.length + 1,
                    controller: _scrollController,
                    physics: const AlwaysScrollableScrollPhysics(),
                    itemBuilder: (BuildContext context, int index) {
                      if (index != RList.length) {
                        return FileSpaceHelper.FtpFileCard(
                            context, RList[index], onDeleted);
                      } else {
                        if (isEnd == true) {
                          return Container(
                              margin: EdgeInsets.all(12.0),
                              child: Center(
                                  child: Text(
                                "没有更多了",
                                style: TextStyle(color: Colors.grey),
                              )));
                        } else {
                          return new Container();
                        }
                      }
                    },
                  ),
                  onRefresh: getNewer,
                )));
  }
}
